import { Component } from "react";
let timer = null
export default class State1Demo extends Component {
    constructor() {
        super();
    }
    state = {
        num: 1,
        flag: true,
        word: ''
    }
    countChange = () => {
        const { flag, num } = this.state
        if (timer) {
            clearInterval(timer)
            timer = null
        } else {
            timer = setInterval(() => {
                this.setState({
                    num: ++this.state.num
                })
            }, 1000)
        }
        this.setState({
            flag: !flag,
        })
    }
    changeWord = (v) => {
        const { word } = this.state
        this.setState({
            word: v.target.value
        })
    }


    childChangeShow = () => {
        this.child.changeShow();
    }
    render() {

        const { flag, num, word } = this.state
        return (
            <div>
                <h3>简易计时器</h3>
                <h4>{num}</h4>
                <p><button onClick={this.countChange}>{flag ? '开始计时' : '暂停计时'}</button></p>
                <p>word --- {word}</p>
                <input type="password" value={word} onChange={this.changeWord} />
                <p>
                    {/* <button onClick={this.childChangeShow}>ref修改子组件</button> */}
                    <button onClick={() => this.child.changeShow()}>ref修改子组件</button>
                </p>
                <hr />
                <Child ref={(el) => this.child = el} />
            </div>
        )
    }
}
class Child extends Component {
    constructor() {
        super()
        this.state = {
            show: true
        }
    }
    changeShow = () => {
        this.setState({

            show: !this.state.show
        })
    }

    render() {
        const { show } = this.state
        return (
            <div>
                <p style={{ display: show ? 'flex' : 'none', backgroundColor: 'pink', width: '200px', height: '200px' }}>父组件通过ref控制子组件显隐</p>
            </div>
        )
    }
}

